import itertools
import numpy as np
from scipy.stats import binom

# 定义每个零配件、半成品和成品的参数
params = {
    "parts": [
        {"id": 1, "p_true": 0.10, "c_b": 2, "c_d": 1, "n": 100},  # 加入了抽样样本量 n
        {"id": 2, "p_true": 0.10, "c_b": 8, "c_d": 1, "n": 100},
        {"id": 3, "p_true": 0.10, "c_b": 12, "c_d": 2, "n": 100},
        {"id": 4, "p_true": 0.10, "c_b": 2, "c_d": 1, "n": 100},
        {"id": 5, "p_true": 0.10, "c_b": 8, "c_d": 1, "n": 100},
        {"id": 6, "p_true": 0.10, "c_b": 12, "c_d": 2, "n": 100},
        {"id": 7, "p_true": 0.10, "c_b": 8, "c_d": 1, "n": 100},
        {"id": 8, "p_true": 0.10, "c_b": 12, "c_d": 2, "n": 100},
    ],
    "half_products": [
        {"id": 1, "p_true": 0.10, "c_a": 8, "c_d": 4, "c_s": 6, "n": 50},
        {"id": 2, "p_true": 0.10, "c_a": 8, "c_d": 4, "c_s": 6, "n": 50},
        {"id": 3, "p_true": 0.10, "c_a": 8, "c_d": 4, "c_s": 6, "n": 50},
    ],
    "final_product": {"p_true": 0.10, "c_a": 8, "c_d": 6, "c_s": 10, "r": 200, "c_swap": 40, "n": 20}
}


# 定义从抽样中估计次品率的函数
def sample_defect_rate(p_true, n, confidence=0.95):
    """
    基于实际的次品率 p_true 和样本量 n，生成次品率的估计值。
    使用二项分布模拟抽样，并基于抽样结果推断次品率。
    """
    # 抽取次品数量
    defects = np.random.binomial(n, p_true)

    # 估计次品率
    p_est = defects / n

    return p_est


# 定义计算总成本和收益的函数
def calculate_costs_and_revenue(decision, params):
    d_parts, d_half_products, d_final_product, s_half_products, s_final_product = decision

    # 零配件部分的检测成本和次品损失
    cost_parts_detection = sum(d_parts[i] * params['parts'][i]['c_d'] for i in range(8))
    cost_parts_loss = sum((1 - d_parts[i]) * sample_defect_rate(params['parts'][i]['p_true'], params['parts'][i]['n']) *
                          params['parts'][i]['c_b'] for i in range(8))

    # 半成品的装配成本、检测成本、次品损失和拆解费用
    cost_half_products_assembly = sum(params['half_products'][i]['c_a'] for i in range(3))
    cost_half_products_detection = sum(d_half_products[i] * params['half_products'][i]['c_d'] for i in range(3))
    cost_half_products_loss = sum((1 - d_half_products[i]) * sample_defect_rate(params['half_products'][i]['p_true'],
                                                                                params['half_products'][i]['n']) *
                                  params['half_products'][i]['c_a'] for i in range(3))
    cost_half_products_scrap = sum(s_half_products[i] * params['half_products'][i]['c_s'] for i in range(3))

    # 成品的装配成本、检测成本、次品损失、调换损失和拆解费用
    cost_final_assembly = params['final_product']['c_a']
    cost_final_detection = d_final_product * params['final_product']['c_d']
    cost_final_loss = (1 - d_final_product) * sample_defect_rate(params['final_product']['p_true'],
                                                                 params['final_product']['n']) * \
                      params['final_product']['c_a']
    cost_final_swap = (1 - d_final_product) * sample_defect_rate(params['final_product']['p_true'],
                                                                 params['final_product']['n']) * \
                      params['final_product']['c_swap']
    cost_final_scrap = s_final_product * params['final_product']['c_s']

    # 总成本
    total_cost = (cost_parts_detection + cost_parts_loss + cost_half_products_assembly + cost_half_products_detection +
                  cost_half_products_loss + cost_half_products_scrap + cost_final_assembly + cost_final_detection +
                  cost_final_loss + cost_final_swap + cost_final_scrap)

    # 收益
    revenue = params['final_product']['r'] * (
                1 - sample_defect_rate(params['final_product']['p_true'], params['final_product']['n']))

    # 净利润
    profit = revenue - total_cost

    return total_cost, revenue, profit


# 暴力求解：遍历所有可能的决策组合
def find_best_decision(params):
    best_decision = None
    best_profit = float('-inf')
    best_cost = None
    best_revenue = None

    # 遍历所有可能的决策组合 (d_parts, d_half_products, d_final_product, s_half_products, s_final_product)
    for decision in itertools.product([0, 1], repeat=14):  # 8 零配件 + 3 半成品 + 1 成品检测 + 3 半成品拆解 + 1 成品拆解
        d_parts = decision[:8]
        d_half_products = decision[8:11]
        d_final_product = decision[11]
        s_half_products = decision[11:14]
        s_final_product = decision[13]

        # 计算成本和收益
        total_cost, revenue, profit = calculate_costs_and_revenue(
            (d_parts, d_half_products, d_final_product, s_half_products, s_final_product), params)

        # 更新最优解
        if profit > best_profit:
            best_profit = profit
            best_decision = decision
            best_cost = total_cost
            best_revenue = revenue

    return best_decision, best_cost, best_revenue, best_profit


# 求解最优方案
best_decision, best_cost, best_revenue, best_profit = find_best_decision(params)

# 输出结果
print(f"最优决策: {best_decision}")
print(f"总成本: {best_cost}")
print(f"总收益: {best_revenue}")
print(f"净利润: {best_profit}")